<template>
  <div class="createPost-container">
    <el-form 
      ref="postForm" 
      :model="postForm" 
      :rules="rules" 
      class="form-container">

      <sticky :class-name="'sub-navbar '+postForm.status">
        <el-button 
          v-loading="loading" 
          style="margin-left: 10px;" 
          type="success" 
          @click="submitForm">发布
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <el-col :span="24">

            <el-form-item 
              style="margin-bottom: 40px;" 
              prop="name">
              <MDinput 
                v-model="postForm.name" 
                :maxlength="100" 
                name="name" 
                required>
                标题
              </MDinput>
            </el-form-item>

            <el-form-item 
              label="分类:" 
              prop="categoryId">
              <el-select 
                v-model="postForm.categoryId" 
                placeholder="分类名">
                <el-option 
                  v-for="item in categoryList" 
                  :value="item.id" 
                  :label="item.name"/>
              </el-select>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item 
                    label-width="45px" 
                    label="作者:" 
                    class="postInfo-container-item" 
                    prop="author">
                    <el-input 
                      v-model="postForm.author" 
                      placeholder="请输入内容"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item 
                    label-width="45px" 
                    label="权重:" 
                    class="postInfo-container-item" 
                    prop="sort">
                    <el-input 
                      v-model="postForm.sort" 
                      placeholder="请输入内容"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item 
                    label-width="80px" 
                    label="发布时间:" 
                    class="postInfo-container-item">
                    <el-date-picker 
                      v-model="postForm.createtime" 
                      type="datetime" 
                      format="yyyy-MM-dd HH:mm:ss" 
                      placeholder="选择日期时间"/>
                  </el-form-item>
                </el-col>

              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item 
          style="margin-bottom: 40px;" 
          label-width="45px" 
          label="摘要:" 
          prop="summary">
          <el-input 
            :rows="1" 
            v-model="postForm.summary" 
            type="textarea" 
            class="article-textarea" 
            autosize 
            placeholder="请输入内容"/>
          <span 
            v-show="contentShortLength" 
            class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <div 
          class="editor-container" 
          prop="content">
          <Tinymce 
            ref="editor" 
            :height="400" 
            v-model="postForm.content" />
        </div>

        <el-form-item 
          label="缩略图:" 
          prop="thumbnail">
          <Upload v-model="postForm.thumbnail" />
        </el-form-item>
      </div>
    </el-form>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/singleImage'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validateURL } from '@/utils/validate'
import { fetchArticle, categoryList, add, del, edit } from '@/api/article'
import { userSearch } from '@/api/remoteSearch'
import Warning from './Warning'

const defaultForm = {
  name: '',
  categoryId: '',
  author: '',
  sort: '',
  createtime: '',
  summary: '',
  content: '',
  thumbnail: ''
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        title: [{ validator: validateRequire }],
        categoryId: [{ validator: validateRequire }],
        createtime: [{ validator: validateRequire }],
        summary: [{ validator: validateRequire }],
        thumbnail: [{ validator: validateRequire }]
      },
      tempRoute: {},
      categoryList: []
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.content.length
    },
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    categoryList().then(response => {
      console.log(response)
      this.categoryList = response.data
    })

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      fetchArticle(id).then(response => {
        this.postForm = response.data.data
        // Set tagsview title
        this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    submitForm() {
      this.postForm.display_time = parseInt(this.display_time / 1000)
      // console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true

          if (this.isEdit) {
            edit(this.postForm).then(response => {
              if (response.data.code == 1) {
                this.$notify({
                  title: '成功',
                  message: '更新文章成功',
                  type: 'success',
                  duration: 2000
                })
                this.loading = false
              } else {
                this.$notify.error({
                  title: '错误',
                  message: res.data.message
                })
                this.loading = false
                return false
              }
            }).catch(err => {
              this.$message({
                showClose: true,
                message: '网络请求失败',
                type: 'error'
              })
              this.loading = false
              return false
            })
          } else {
            add(this.postForm).then(response => {
              if (response.data.code == 1) {
                this.$notify({
                  title: '成功',
                  message: '发布文章成功',
                  type: 'success',
                  duration: 2000
                })
                this.loading = false
              } else {
                this.$notify.error({
                  title: '错误',
                  message: res.data.message
                })
                this.loading = false
                return false
              }
            }).catch(err => {
              this.$message({
                showClose: true,
                message: '网络请求失败',
                type: 'error'
              })
              this.loading = false
              return false
            })
          }
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 1)
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
    .editor-container {
      min-height: 500px;
      margin: 0 0 30px;
      .editor-upload-btn-container {
        text-align: right;
        margin-right: 10px;
        .editor-upload-btn {
          display: inline-block;
        }
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
